package com.example.springbootauthenticationjwt.contorller;

import com.example.springbootauthenticationjwt.entity.User;
import com.example.springbootauthenticationjwt.entity.UserRequest;
import com.example.springbootauthenticationjwt.entity.UserResponse;
import com.example.springbootauthenticationjwt.jwt.JWTUtil;
import com.example.springbootauthenticationjwt.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping(value = "/saveUser",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> saveUser(@RequestBody User user){
        Integer userId = userService.saveUser(user);
        String message = String.format("User with id '%d' saved successfully",userId);
        return new ResponseEntity<>(message, HttpStatus.OK);
    }

    @PostMapping(value = "/loginUser",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UserResponse> login(@RequestBody UserRequest userRequest){
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userRequest.getUsername(),userRequest.getPassword()));
        String token = jwtUtil.generateToken(userRequest.getUsername());
        UserResponse userResponse = new UserResponse();
        userResponse.setMessage("Token generate successfully");
        userResponse.setToken(token);
        return new ResponseEntity<>(userResponse,HttpStatus.OK);
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @PostMapping(value = "/getData",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> restAfterLogin(Principal principal){
        return new ResponseEntity<>("Your are accessing data after a valid Login,your name is " + principal.getName(),HttpStatus.OK);
    }
}
